package com.aibili.contoller.api;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.aibili.pojo.ChargeCard;
import com.aibili.pojo.ChargeRecord;
import com.aibili.pojo.EventUser;
import com.aibili.pojo.GiftInfo;
import com.aibili.pojo.GiftRecord;
import com.aibili.pojo.LvInfo;
import com.aibili.pojo.UserAccount;
import com.aibili.pojo.UserInfo;
import com.aibili.service.AnonymousService;
import com.aibili.service.EventService;
import com.aibili.service.GiftService;
import com.aibili.service.UserFavorabilityService;
import com.aibili.service.UserInfoService;
import com.alibaba.fastjson.JSON;
import com.alipay.config.AlipayConfig;
import com.alipay.util.UtilDate;
import com.daoshun.common.CommonUtils;
import com.daoshun.common.DsConstant;
import com.daoshun.exception.CustomException;

@Controller
@RequestMapping("/api/gift")
public class ApiGiftContoller extends ApiBaseContoller {

	@Resource
	private GiftService giftService;

	@Resource
	private UserInfoService userInfoService;

	@Resource
	private UserFavorabilityService userFavorabilityService;

	@Resource
	private EventService eventService;

	@Resource
	private AnonymousService anonymousService;

	/**
	 * 送礼物
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/give", produces = "application/json; charset=UTF-8")
	public String give(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			request.setCharacterEncoding("utf-8");
			String from_id = request.getParameter("from_id");
			String mobile = request.getParameter("mobile");
			String gift_id = request.getParameter("gift_id");
			CommonUtils.validateEmpty(from_id);
			CommonUtils.validateEmpty(gift_id);
			long uid = CommonUtils.parseLong(from_id, 0);
			long gid = CommonUtils.parseLong(gift_id, 0);
			long to_id = 0;
			String anon_id = "";
			if (!CommonUtils.isEmptyString(mobile)) {
				CommonUtils.validateEmpty(mobile);
				UserInfo info = userInfoService.getUserByPhone(mobile);
				if (info != null) {
					to_id = info.getId();
					UserInfo user = userInfoService.getById(uid);
					int money = user.getPoint();
					GiftRecord record = new GiftRecord();
					if (gid==1) {
						if(money<0){//2
							return DsConstant.BALANCE_NOT_ENOUGH;
						}else{
							ChargeRecord chargeRecord = new ChargeRecord();
							chargeRecord.setCharge_num(0);//扣U币记录-2
							chargeRecord.setCharge_time(new Date());
							chargeRecord.setUser_id(user.getId());
							chargeRecord.setProportion(0);
							chargeRecord.setGift_ids(2);
							giftService.SaveChargeRecord(chargeRecord);
							user.setPoint(user.getPoint()-0);//发起方扣U币-2
							user.setExp(user.getExp()+(2*2));
							LvInfo lvInfo = userInfoService.getLvInfoByLv(user.getLevel());
							if (lvInfo!=null &&user.getExp()+(2*2)>(lvInfo.getExp()+lvInfo.getTotal())) {
								user.setLevel(user.getLevel()+1);
							}
							info.setExp(info.getExp()+2);
							ChargeRecord chargeRecord2 = new ChargeRecord();
							chargeRecord2.setMoney(0);//接收方加钱记录+2*0.9
							chargeRecord2.setCharge_time(new Date());
							chargeRecord2.setUser_id(info.getId());
							chargeRecord2.setProportion(0);
							chargeRecord2.setGift_ids(3);
							giftService.SaveChargeRecord(chargeRecord2);
							info.setMoney(info.getMoney()+(0));//接收方加钱+2*0.9
							LvInfo lvInfo2 = userInfoService.getLvInfoByLv(info.getLevel());
							if (lvInfo2!=null && info.getExp()+2>(lvInfo2.getExp()+lvInfo2.getTotal())) {
								info.setLevel(info.getLevel()+1);
							}
							record.setPoint(2);
						}
					}
					if (gid==2) {
						if (money<0) {//5
							return DsConstant.BALANCE_NOT_ENOUGH;
						}else{
							ChargeRecord chargeRecord = new ChargeRecord();
							chargeRecord.setCharge_num(-0);//扣U币记录-5
							chargeRecord.setCharge_time(new Date());
							chargeRecord.setUser_id(user.getId());
							
							chargeRecord.setProportion(0);
							chargeRecord.setGift_ids(4);
							giftService.SaveChargeRecord(chargeRecord);
							user.setPoint(user.getPoint()-0);//发起视频者U币-5
							user.setExp(user.getExp()+(2*5));
							LvInfo lvInfo = userInfoService.getLvInfoByLv(user.getLevel());
							if (lvInfo!=null &&user.getExp()+(2*5)>(lvInfo.getExp()+lvInfo.getTotal())) {
								user.setLevel(user.getLevel()+1);
							}
							ChargeRecord chargeRecord2 = new ChargeRecord();
							chargeRecord2.setMoney(0);//接受视频者收钱记录+5*0.9
							chargeRecord2.setCharge_time(new Date());
							chargeRecord2.setUser_id(info.getId());
							chargeRecord2.setProportion(0);
							chargeRecord2.setGift_ids(5);
							giftService.SaveChargeRecord(chargeRecord2);
							info.setMoney(info.getMoney()+(0));//接受视频者收钱+5*0.9
							info.setExp(info.getExp()+10);
							LvInfo lvInfo2 = userInfoService.getLvInfoByLv(info.getLevel());
							if (lvInfo2!=null && info.getExp()+10>(lvInfo2.getExp()+lvInfo2.getTotal())) {
								info.setLevel(info.getLevel()+1);
							}
							record.setPoint(5);
						}
					}
					record.setFrom_id(uid);
					record.setGift_id(gid);
					record.setTo_id(to_id);
					record.setIs_change(0);
					record.setAnonymous_id(anon_id);
					record.setReceive_time(new Date());
					// 添加送礼物记录
					giftService.SaveGiftRecord(record);
					userInfoService.updateUserInfo(user);
					userInfoService.updateUserInfo(info);
					map.put("user",user );
					map.putAll(DsConstant.SUCCESS_RESULT_MAP);
				} else {
					return DsConstant.NO_USER;
				}
			} 
			return JSON.toJSONString(map);
		} catch (CustomException e) {
			return e.getMessage();
		} catch (Exception e) {
			e.printStackTrace();
			return DsConstant.EXCEPTION;
		}
	}

	/**
	 * 
	 * @Description 改活动送礼物
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/givetoevent", produces = "application/json; charset=UTF-8")
	public String giveToEvent(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			request.setCharacterEncoding("utf-8");
			String user_id = request.getParameter("user_id");
			String event_id = request.getParameter("event_id");
			String gift_id = request.getParameter("gift_id");
			String gift_name = request.getParameter("gift_name");
			CommonUtils.validateEmpty(user_id);
			CommonUtils.validateEmpty(event_id);
			CommonUtils.validateEmpty(gift_id);
			CommonUtils.validateEmpty(gift_name);
			long uid = CommonUtils.parseLong(user_id, 0);
			long eid = CommonUtils.parseLong(event_id, 0);
			long gid = CommonUtils.parseLong(gift_id, 0);

			UserInfo user = userInfoService.getById(uid);
			GiftInfo gift = giftService.getGiftInfo(gid);
			if (user != null && gift != null) {
				if (user.getPoint() < gift.getPoint()) {
					return DsConstant.BALANCE_NOT_ENOUGH;
				} else {
					EventUser eventuser = new EventUser();
					eventuser.setEvent_id(eid);
					eventuser.setGift_id(gid);
					eventuser.setJoin_time(new Date());
					eventuser.setGift_name(gift_name);
					eventuser.setUser(user);

					eventService.addEventUser(eventuser);

					// 减少爱币数,添加经验值
					user.setExp(user.getExp() + gift.getPoint());
					user.setPoint(user.getPoint() - gift.getPoint());
					userInfoService.updateUserInfo(user);
					map.putAll(DsConstant.SUCCESS_RESULT_MAP);
					return JSON.toJSONString(map);
				}
			} else {
				return DsConstant.NO_USER;
			}

		} catch (CustomException e) {
			return e.getMessage();
		} catch (Exception e) {
			e.printStackTrace();
			return DsConstant.EXCEPTION;
		}
	}

	/**
	 * 充值
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/charge", produces = "application/json; charset=UTF-8")
	public String charge(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			request.setCharacterEncoding("utf-8");
			String user_id = request.getParameter("user_id");
			String point = request.getParameter("point");
			String type = request.getParameter("type");
			CommonUtils.validateEmpty(user_id);
			CommonUtils.validateEmpty(point);
			CommonUtils.validateEmpty(type);
			UserInfo user = userInfoService.getById(CommonUtils.parseLong(user_id, 0));
			if (user != null) {
//				user.setPoint(user.getPoint() + CommonUtils.parseInt(point, 0));
//				userInfoService.updateUserInfo(user);
				ChargeRecord record = new ChargeRecord();
				record.setCharge_num(CommonUtils.parseInt(point, 0));
				record.setUser_id(CommonUtils.parseLong(user_id, 0));
				record.setCharge_time(new Date());
				record.setGift_ids(0);
				record.setProportion(0);
				record.setType(CommonUtils.parseInt(type, 0));
				record.setFlg(0);
				
				//支付宝
				AlipayConfig alipayConfig = new AlipayConfig();
				String partner = alipayConfig.partner;
				String  private_key = alipayConfig.private_key;
				String seller_id = alipayConfig.seller_id;
				String notify_url = alipayConfig.notify_url;
				
				String out_trade_no = UtilDate.getOrderNum()+UtilDate.getThree()+user.getId();
				record.setAlipayordernum(out_trade_no);
				giftService.SaveChargeRecord(record);
				map.put("user", user);
				map.put("partner", partner);
				map.put("private_key", private_key);
				map.put("total_fee", 0.01);
				map.put("out_trade_no", out_trade_no);
				map.put("subject", "账户充值");
				map.put("body", "U币充值");
				map.put("seller_id", seller_id);
				map.put("notify_url", notify_url);
				map.putAll(DsConstant.SUCCESS_RESULT_MAP);
				return JSON.toJSONString(map);
			} else {
				return DsConstant.NO_USER;
			}
		} catch (CustomException e) {
			return e.getMessage();
		} catch (Exception e) {
			e.printStackTrace();
			return DsConstant.EXCEPTION;
		}
	}

	/**
	 * 提现
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/cash", produces = "application/json; charset=UTF-8")
	public String cash(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			request.setCharacterEncoding("utf-8");
			String user_id = request.getParameter("user_id");
			String money_num = request.getParameter("money_num"); 
			String paypassword = request.getParameter("paypassword");
			CommonUtils.validateEmpty(user_id);
			CommonUtils.validateEmpty(money_num);
			CommonUtils.validateEmpty(paypassword);
			double moneynum = CommonUtils.parseFloat(money_num, 0);
			UserInfo user = userInfoService.getById(CommonUtils.parseLong(user_id, 0));
			if (user!=null) {
				if(user.getPaypassword().equals(paypassword)){
			ChargeRecord record = new ChargeRecord();
			record.setMoney(-moneynum);
			record.setCharge_time(new Date());
			record.setGift_ids(1);
			record.setProportion(1);//改为申请提现
			record.setType(1);
			String out_trade_no = UtilDate.getDate()+UtilDate.getThree()+user.getId();
			record.setAlipayordernum(out_trade_no);
			record.setUser_id(user.getId());
			if(user.getMoney()>moneynum){
			user.setMoney(user.getMoney()-moneynum);
			}else{
				return DsConstant.NOMONEY;
			}
			giftService.SaveChargeRecord(record);
			userInfoService.updateUserInfo(user);
			}else{
				return DsConstant.WRONGPAYPASSWORD;
			}
			map.put("user", user);
			map.putAll(DsConstant.SUCCESS_RESULT_MAP);
			}
			return JSON.toJSONString(map);
		} catch (CustomException e) {
			return e.getMessage();
		} catch (Exception e) {
			e.printStackTrace();
			return DsConstant.EXCEPTION;
		}
		
	}

	/**
	 * 绑定支付信息
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/bind", produces = "application/json; charset=UTF-8")
	public String bind(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			request.setCharacterEncoding("utf-8");
			String user_id = request.getParameter("user_id");
			String card_num = request.getParameter("card_num");
			String mobile = request.getParameter("mobile");
			String vcode = request.getParameter("vcode");
			String paypassword = request.getParameter("paypassword");
			
			CommonUtils.validateEmpty(user_id);
			CommonUtils.validateEmpty(card_num);
			CommonUtils.validateEmpty(mobile);
			CommonUtils.validateEmpty(vcode);
			CommonUtils.validateEmpty(paypassword);
			
			long count = userInfoService.getPhoneCode(mobile, vcode);
			if (count == 0) {
				return DsConstant.VCODEERROR;
			}
			UserAccount account1 = userInfoService.getUserAccountByUseridCard(CommonUtils.parseLong(user_id, 0),
					card_num);
			if (account1 != null) {
				return DsConstant.ACCOUNT_EXSIT;
			} else {
				UserAccount account = new UserAccount();
				account.setCard_num(card_num);
				account.setType(1);
				account.setUser_id(CommonUtils.parseLong(user_id, 0));
				UserInfo user = userInfoService.getById(CommonUtils.parseLong(user_id, 0));
				if (user!=null) {
					user.setPaypassword(paypassword);
					user.setCard_num(card_num);
					userInfoService.updateUserInfo(user);
				}
				// 新增绑定支付信息
				giftService.SaveUserAccount(account);
				map.put("user", user);
				map.putAll(DsConstant.SUCCESS_RESULT_MAP);
				return JSON.toJSONString(map);
			}

		} catch (CustomException e) {
			return e.getMessage();
		} catch (Exception e) {
			e.printStackTrace();
			return DsConstant.EXCEPTION;
		}
	}

	/**
	 * 收到的礼物
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/mygift", produces = "application/json; charset=UTF-8")
	public String mygift(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			request.setCharacterEncoding("utf-8");
			// 收到人id
			String user_id = request.getParameter("user_id");
			String page = request.getParameter("page");
			if (CommonUtils.isEmptyString(page)) {
				page = "1";
			}
			CommonUtils.validateEmpty(user_id);
			// 我收到的礼物
			List<GiftRecord> gift_list = giftService.getMyGetGiftList(CommonUtils.parseLong(user_id, 0),
					CommonUtils.parseInt(page, 0), DsConstant.GIFTPAGESIZE);
			map.put("gift_list", gift_list);
			map.putAll(DsConstant.SUCCESS_RESULT_MAP);
			return toJson(map);
		} catch (CustomException e) {
			return e.getMessage();
		} catch (Exception e) {
			e.printStackTrace();
			return DsConstant.EXCEPTION;
		}
	}

	/**
	 * 情感中心
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/mysend", produces = "application/json; charset=UTF-8")
	public String mysend(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			request.setCharacterEncoding("utf-8");
			// 送出人id
			String user_id = request.getParameter("user_id");
			String page = request.getParameter("page");
			if (CommonUtils.isEmptyString(page)) {
				page = "1";
			}
			CommonUtils.validateEmpty(user_id);
			// 我送出的礼物
			List<GiftRecord> gift_list = giftService.getMySendGiftList(CommonUtils.parseLong(user_id, 0),
					CommonUtils.parseInt(page, 0), DsConstant.GIFTPAGESIZE);
			// 送出的总份数
			int total_num = giftService.getMySendGiftCount(CommonUtils.parseLong(user_id, 0));
			// 送出的送爱币数
			long total_point = giftService.getMySendGiftPoint(CommonUtils.parseLong(user_id, 0));
			map.put("gift_list", gift_list);
			map.put("total_num", total_num);
			map.put("total_point", total_point);
			map.putAll(DsConstant.SUCCESS_RESULT_MAP);
			return toJson(map);
		} catch (CustomException e) {
			return e.getMessage();
		} catch (Exception e) {
			e.printStackTrace();
			return DsConstant.EXCEPTION;
		}
	}

	/**
	 * 消费记录
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/record", produces = "application/json; charset=UTF-8")
	public String record(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			request.setCharacterEncoding("utf-8");
			// 送出人id
			String user_id = request.getParameter("user_id");
			String page = request.getParameter("page");
			if (CommonUtils.isEmptyString(page)) {
				page = "1";
			}
			CommonUtils.validateEmpty(user_id);
			List<ChargeRecord> record_list = giftService.getChargeRecordByUser(CommonUtils.parseLong(user_id, 0),
					CommonUtils.parseInt(page, 0));
			map.put("record_list", record_list);
			map.putAll(DsConstant.SUCCESS_RESULT_MAP);
			return toJson(map);
		} catch (CustomException e) {
			return e.getMessage();
		} catch (Exception e) {
			e.printStackTrace();
			return DsConstant.EXCEPTION;
		}
	}

	/**
	 * 礼物列表
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/list", produces = "application/json; charset=UTF-8")
	public String list(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			request.setCharacterEncoding("utf-8");
			// 礼物类型
			String type = request.getParameter("type");
			CommonUtils.validateEmpty(type);
			List<GiftInfo> gift_list = giftService.getGiftList(CommonUtils.parseInt(type, 0));
			map.put("gift_list", gift_list);
			map.putAll(DsConstant.SUCCESS_RESULT_MAP);
			return toJson(map);
		} catch (CustomException e) {
			return e.getMessage();
		} catch (Exception e) {
			e.printStackTrace();
			return DsConstant.EXCEPTION;
		}
	}

	/**
	 * 
	 * @Description 充值卡列表
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/chargecard_list", produces = "application/json; charset=UTF-8")
	public String chargecardlist(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			request.setCharacterEncoding("utf-8");
			// 礼物类型
			List<ChargeCard> list = giftService.getChargeCard();
			map.put("chargecard_list", list);
			return toSuccessJson(map);
		} catch (Exception e) {
			e.printStackTrace();
			return DsConstant.EXCEPTION;
		}
	}

	
}
